package code._16reflect._03constructor;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Demo {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //获取字节码文件对象
        Class<?> personCls = Class.forName("code._16reflect.bean.Person");
        //通过反射获取所有的构造方法
        System.out.println("--------通过反射获取所有的public构造方法-----------");
        Constructor<?>[] constructors = personCls.getConstructors();
        //遍历输出
        for (Constructor<?> constructor : constructors) {
            System.out.println( constructor);
        }

        System.out.println("--------通过反射获取所有的构造方法-----------");
        Constructor<?>[] declaredConstructors = personCls.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }

        System.out.println("-----获取指定的public构造方法------");
        // Constructor<T> getConstructor(Class<?>... parameterTypes)
        Constructor<?> noArgsConstructor = personCls.getConstructor();
        System.out.println(noArgsConstructor);


        System.out.println("-----获取指定的构造方法------");
        //Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
        Constructor<?> declaredConstructor = personCls.getDeclaredConstructor(String.class, int.class);
        System.out.println(declaredConstructor);

        //通过构造器实例化对象
        System.out.println("----通过构造器实例化对象-----");
        Object o = noArgsConstructor.newInstance();
        System.out.println("o = " + o);
        //忽略Java语法检查
        declaredConstructor.setAccessible(true);
        Object o1 = declaredConstructor.newInstance("ls", 21);
        System.out.println("o1 = " + o1);
    }
}
